package com.tool4j.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tool4j.entity.AiSessionLog;
import com.tool4j.entity.GenerateCodeLog;
import com.tool4j.entity.params.ChatParams;
import com.tool4j.entity.params.PageParams;
import com.tool4j.mapper.AiSessionLogMapper;
import com.tool4j.service.AiSessionLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AiSessionLogServiceImpl extends ServiceImpl<AiSessionLogMapper, AiSessionLog> implements AiSessionLogService {

    @Autowired
    private AiSessionLogMapper sessionLogMapper;

    @Override
    public void saveIfNotExists(ChatParams params) {
        if (StrUtil.isNotBlank(params.getSessionId())) {
            AiSessionLog exists = sessionLogMapper.selectById(Long.parseLong(params.getSessionId()));
            if (exists != null) {
                exists.setUpdatedDate(new Date());
                sessionLogMapper.updateById(exists);
                return;
            }
        }
        AiSessionLog log = new AiSessionLog();
        log.setId(Long.parseLong(params.getSessionId()));
        log.setUserId(params.getUserId());
        log.setTitle(params.getContent());
        sessionLogMapper.insert(log);
    }

    @Override
    public Page<AiSessionLog> findPage(Long userId, PageParams<AiSessionLog> params) {
        LambdaQueryWrapper<AiSessionLog> query = Wrappers.lambdaQuery(AiSessionLog.class)
                .eq(AiSessionLog::getUserId, userId)
                .like(params.getParams() != null && StrUtil.isNotBlank(params.getParams().getSearchInput()), AiSessionLog::getSearchInput, params.getParams().getSearchInput())
                .orderByDesc(AiSessionLog::getCreatedDate);
        Page<AiSessionLog> page = params.getPage().setOptimizeCountSql(false);
        return sessionLogMapper.selectPage(page, query);
    }

    @Override
    public void deleteSession(Long userId, Long id) {
        LambdaQueryWrapper<AiSessionLog> query = Wrappers.lambdaQuery(AiSessionLog.class)
                .eq(AiSessionLog::getUserId, userId)
                .eq(AiSessionLog::getId, id);
        sessionLogMapper.delete(query);
    }

    @Override
    public void deleteAllSession(Long userId) {
        LambdaQueryWrapper<AiSessionLog> query = Wrappers.lambdaQuery(AiSessionLog.class)
                .eq(AiSessionLog::getUserId, userId);
        sessionLogMapper.delete(query);
    }
}
